package cn.boodqian.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import junit.framework.Assert;

public class GAERequest {
	//private final static String[] m_IPs = new String[] {"203.208.46.1","203.208.46.2","203.208.46.3","203.208.46.4","203.208.46.5","203.208.46.6","203.208.46.7","203.208.46.8"};
	private final static String[] m_IPs = new String[] {"203.208.47.1","203.208.47.2","203.208.47.3","203.208.47.4","203.208.47.5","203.208.47.6","203.208.47.7","203.208.47.8"};
	//private final static String[] m_IPs = new String[] {"10.0.2.2:8888"};
	public static Integer mLastIPIndex = 0;
	private String appname;
	private String hostname;
	private String lasterror = "";
	private final static String m_UrlFormat = "http://%s%s";
	private final static String m_HostFormat = "%s.appspot.com";
	public GAERequest(String appname) {
		assert(appname!=null && appname.length()>0);
		this.appname = appname;
		this.hostname = String.format(m_HostFormat, appname);
	}
	// path: "/airdata"
	public String doGet(String path) {
		Assert.assertTrue(path, path.startsWith("/"));
		Log.i("Requesting="+path);
		StringBuilder builder = new StringBuilder();
		for(int i=0;i<m_IPs.length;i++) {
			URL url;
			try {
				String ip = m_IPs[i];
				
				// Try last success IP first
				synchronized(mLastIPIndex) {
					if( i == 0 && mLastIPIndex < m_IPs.length ) {
						ip = m_IPs[mLastIPIndex];
					} else if( i == mLastIPIndex ) {
						ip = m_IPs[0];
					}
				}
				
				Log.i("Trying "+ip);
				url = new URL(String.format(m_UrlFormat, ip, path));
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setRequestProperty("Host", hostname);
				connection.setConnectTimeout(10000);
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				
				// Find out the success IP index
				synchronized(mLastIPIndex) {
					for( int j=0;j<m_IPs.length;j++ ) {
						if( ip.compareTo(m_IPs[j]) == 0 ) {
							mLastIPIndex = j;
							break;
						}
					}
				}
				break;
			} catch (Exception e) {
				builder.setLength(0);
				e.printStackTrace();
				lasterror = e.toString();
			}
		}
		//Log.i("Response="+builder.toString());
		String ret = null;
		if(builder.length()>0)  ret=builder.toString();
		return ret;
	}
	
	public String getLastError() {
		return lasterror;
	}
}
